<template>
  <div class="v-edit" v-if="init">
    <el-dialog
        :append-to-body="true"
        :close-on-click-modal="false"
        :show-close="false"
        v-model="visible"
        width="800"
        class="edit-dialog"
    >
      <template #header>
        <div class="flex justify-between items-center my-header">
          <h4 class="text-xl font-bold">{{ title }}</h4>
          <XIcon class="w-4 h-4 cursor-pointer" @click="close"/>
        </div>
      </template>
      <el-scrollbar>
        <el-form
            ref="formRef"
            class="v-form"
            :disabled="isView"
            :model="infos"
            :rules="rules"
        >
          <div>
            <slot name="formItem"></slot>
          </div>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="mr-2" @click="close">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, watch, computed, getCurrentInstance} from "vue";
import {ElDialog} from "element-plus";

const {proxy} = getCurrentInstance();
// Props
const props = defineProps({
  init: {
    type: Object,
    default: null,
  },
  infos: {
    type: Object,
    default: () => ({}),
  },
  rules: {
    type: Object,
    default: () => ({}),
  },
  title:{
    type: String,
    default: ""
  }
});
const formRef = ref(null);
// Refs and state
const visible = ref(false);
// const user = ref($userInfor());
const info = ref({});

// Computed
const isView = computed(() => props.init && props.init.isView);

// Methods
const reset = (bubble) => {
  if (props.init) {
    if (!props.init.isAdd) {
      proxy.$propsCopy(info.value, props.init);
    }
  } else {
    proxy.$propsEmpty(info.value);
  }
  if (bubble) {
    emit("reset");
    formRef.value.resetFields();
  }
};

const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      emit("save", info.value);
    }
  });
};

const submit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      emit("submit", info.value);
    }
  });
};
const close = () => {
  visible.value = false;
  emit("close");
};
// Watchers
watch(
    () => props.init,
    () => {
      visible.value = true;
      reset();
    }
);

// Emit
const emit = defineEmits(["reset", "save", "submit", "close"]);
</script>

<style lang="scss" >
/* Add any required styles here */
.edit-dialog {
  padding: 0 !important;
}

.my-header {
  border-bottom: 1px solid #eeeeee;
  padding: 10px !important;
}
.dialog-footer {
  border-top: 1px solid #eeeeee;
  padding: 10px !important;
}
</style>